import React, { useState } from 'react';
import styles from '../qian/Logins.module.css';
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';

export default function LoginPage() {
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    rememberMe: false
  });
  const [loading, setLoading] = useState(false);

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    
    try {
      // 基本验证
      if (!formData.username || !formData.password) {
        throw new Error('用户名和密码不能为空');
      }

      const response = await fetch('http://localhost:3001/logins', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: formData.username,
          password: formData.password
        })
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || '登录失败');
      }

      message.success('登录成功');
      
      // 存储token到本地
      if (data.token) {
        localStorage.setItem('token', data.token);
        console.log('Token已存储:', data.token.substring(0, 20) + '...');
      } else {
        console.warn('登录响应中没有token');
      }
      
      // 存储用户信息到本地
      localStorage.setItem('currentUser', JSON.stringify({
        username: formData.username,
        // 可以根据后端返回的数据添加更多用户信息
        ...data.user
      }));

      navigate('/houtai');
      
    } catch (error) {
      message.error(error.message || '登录失败');
      console.error('登录错误:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.loginContainer}>
      <div className={styles.background}></div>
      
      <div className={styles.loginBox}>
        <div className={styles.header}>
          <h1 className={styles.logo}>登录</h1>
        </div>
        
        <form className={styles.form} onSubmit={handleSubmit}>
          <div className={styles.inputGroup}>
            <input
              type="text"
              name="username"
              placeholder="请输入用户名"
              className={styles.input}
              value={formData.username}
              onChange={handleChange}
              required
            />
          </div>
          
          <div className={styles.inputGroup}>
            <input
              type="password"
              name="password"
              placeholder="请输入密码"
              className={styles.input}
              value={formData.password}
              onChange={handleChange}
              required
            />
          </div>
          
          <div className={styles.agreement}>
            <p>登录即同意<a href="#">电子章服务协议</a>，<a href="#">隐私政策</a>和<a href="#">数字证书申请协议</a></p>
          </div>
          
          <button 
            type="submit" 
            className={styles.loginButton}
            disabled={loading}
          >
            {loading ? '登录中...' : '同意协议并登录'}
          </button>
          
          <div className={styles.options}>
            <label className={styles.rememberMe}>
              <input
                type="checkbox"
                name="rememberMe"
                checked={formData.rememberMe}
                onChange={handleChange}
              />
              <span>记住我</span>
            </label>
          </div>
        </form>
      </div>
    </div>
  );
}